package com.wanqing.service.impl;

import com.wanqing.context.BaseContext;
import com.wanqing.dto.ShoppingCartDTO;
import com.wanqing.entity.Book;
import com.wanqing.entity.ShoppingCart;
import com.wanqing.exception.BaseException;
import com.wanqing.mapper.BookMapper;
import com.wanqing.mapper.BookListMapper;
import com.wanqing.mapper.ShoppingCartMapper;
import com.wanqing.service.ShoppingCartService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.util.List;

/**
 * 购物车服务实现类
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private BookMapper bookMapper;
    @Resource
    private BookListMapper bookListMapper;

    /**
     * 添加购物车
     *
     * @param shoppingCartDTO 购物车DTO
     */
    @Override
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        Long userId;
        //处理各种业务异常（地址簿为空，购物车数据为空）
        if (shoppingCartDTO.getUserId()==null){
            userId = BaseContext.getCurrentId();
        }else {
            userId = shoppingCartDTO.getUserId();
        }
        //判断当前加入到购物车中的商品是否已经存在了
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        //如果已经存在，只需要将数量加1
        if (list != null && !list.isEmpty()) {
            ShoppingCart cart = list.get(0);
            cart.setNumber(cart.getNumber() + 1);
            shoppingCartMapper.updateNumberById(cart);
        } else {
            //如果不存在，需要插入一条购物车数据
            //判断本次添加到购物车的是图书还是书单
            Long bookId = shoppingCartDTO.getBookId();
            if (bookId != null) {
                //本次添加到购物车的是图书
                Book book = bookMapper.getById(bookId);
                if (book == null) {
                    throw new BaseException("图书不存在");
                }
                shoppingCart.setName(book.getName());
                shoppingCart.setImage(book.getImage());
                shoppingCart.setAmount(book.getPrice());
            } else {
                Long bookListId = shoppingCartDTO.getBookListId();
                if (bookListId != null) {
                    //本次添加到购物车的是书单
                    com.wanqing.entity.BookList bookList = bookListMapper.getById(bookListId);
                    if (bookList == null) {
                        throw new BaseException("书单不存在");
                    }
                    shoppingCart.setName(bookList.getName());
                    shoppingCart.setImage(bookList.getImage());
                    shoppingCart.setAmount(bookList.getPrice());
                }
            }
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 显示购物车内容
     * <p>
     * 此方法用于获取当前用户的购物车信息它首先确定当前用户的身份，
     * 然后根据用户ID构建一个购物车对象，最后调用购物车映射器的list方法
     * 来获取与该用户关联的所有购物车项
     *
     * @return 包含当前用户购物车中所有项目的列表
     */
    @Override
    public List<ShoppingCart> showShoppingCart(Long userId) {
        // 获取当前用户ID
        if (userId==null){
            userId = BaseContext.getCurrentId();
        }
        // 构建一个带有用户ID的购物车对象
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();
        // 调用购物车映射器的list方法，获取并返回购物车列表
        return shoppingCartMapper.list(shoppingCart);
    }

    /**
     * 清空购物车
     */
    @Override
    public void cleanShoppingCart(Long userId) {
        // 获取当前用户ID
        if (userId==null){
            userId = BaseContext.getCurrentId();
        }
        shoppingCartMapper.deleteByUserId(userId);
    }

    /**
     * 减少购物车中的商品数量
     *
     * @param shoppingCartDTO 购物车DTO
     */
    @Override
    public void subShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        // 获取当前用户ID
        Long userId;
        if (shoppingCartDTO.getUserId()==null){
            userId = BaseContext.getCurrentId();
        }else {
            userId = shoppingCartDTO.getUserId();
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
        //设置查询条件，查询当前登录用户的购物车数据
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

        if (list != null && !list.isEmpty()) {
            shoppingCart = list.get(0);
            Integer number = shoppingCart.getNumber();
            if (number == 1) {
                //当前商品在购物车中的份数为1，直接删除当前记录
                shoppingCartMapper.deleteById(shoppingCart.getId());
            } else {
                //当前商品在购物车中的份数不为1，修改份数即可
                shoppingCart.setNumber(shoppingCart.getNumber() - 1);
                shoppingCartMapper.updateNumberById(shoppingCart);
            }
        }
    }
}

